package websocket

import (
	"net/http"
	"sen-golang-study/go_game_study/hero_story_go_server/common/log"
	"sen-golang-study/go_game_study/hero_story_go_server/gateway_server/internal/application/services"
)

type Handler struct {
	upgrader       *Upgrader
	gatewayService *services.GatewayService
}

func NewHandler(upgrader *Upgrader, gatewayService *services.GatewayService) *Handler {
	return &Handler{
		upgrader:       upgrader,
		gatewayService: gatewayService,
	}
}

func (h *Handler) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
	if w == nil || r == nil {
		return
	}

	conn, err := h.upgrader.Upgrade(w, r)
	if err != nil {
		log.Error("WebSocket upgrade error, %v+", err)
		return
	}

	defer func() {
		_ = conn.Close()
	}()

	log.Info("有新客户端连入")
	h.gatewayService.HandleWebSocketConnection(conn)
}
